package com.liu.atomicDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {
    public static void main(String[] args) throws InterruptedException {
        AtomicLock atomicLock = new AtomicLock();
        new Thread(() ->{
            try {
                atomicLock.lock();
                TimeUnit.MILLISECONDS.sleep(1000);//睡5秒
                atomicLock.unlock();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"A").start();
        TimeUnit.MILLISECONDS.sleep(500);
        new Thread(() ->{
            atomicLock.lock();
            System.out.println("线程B在运行");
            atomicLock.unlock();
        },"B").start();
    }
}

class AtomicLock{
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    public void lock(){
        System.out.println(Thread.currentThread() + "come lock");
        Thread thread = Thread.currentThread();
        while(!atomicReference.compareAndSet(null,thread)) {
            System.out.println(thread + "正在自旋拿锁");
        }
    }

    public void unlock(){
        System.out.println(Thread.currentThread() + "come in unlock");
        atomicReference.compareAndSet(Thread.currentThread(),null);
        System.out.println(Thread.currentThread() + "释放锁");
    }

}
